import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { SimpleAnimate } from '../../../share/animation/my.simple.animation';

import { HttpService } from '../../../share/http/http.service';
import { NoticeService } from '../../../share/service/notice.service';

import { Menu } from '../../../system/model/menu.model';

@Component({
  selector: 'hk-menu-edit',
  templateUrl: './menu.edit.component.html',
  styleUrls: ['./menu.edit.component.css'],
  animations: [SimpleAnimate]
})
export class MenuEditComponent implements OnInit {

  private nothingMenu = new Menu();

  private pids: number[] = [];

  id: number;
  type: number; // 判断，添加或编辑

  menu: Menu = new Menu();

  menuArray: any[] = [];

  constructor(
    private httpService: HttpService,
    private noticeService: NoticeService,
    private route: ActivatedRoute,
    private router: Router) { }


  ngOnInit() {

    this.nothingMenu.name = '--无--';
    this.nothingMenu.id = null;

    this.getMenuArray();
    this.route.params.subscribe((params: Params) => {
      this.id = parseInt(params['id'], 10);
      this.type = parseInt(params['type'], 10);
      if (this.type && this.id) {
        this.getById();
      } else {
        this.menu.pid = this.id ? this.id : null;
      }
    });
  }

  back() {
    this.router.navigate(['/main/menu/list']);
  }

  save() {
    let body = this.menu;
    if (this.menu.pid && this.menuArray) {
      this.getPids(this.menu.pid);
      this.pids.reverse();
      this.menu.pids = this.pids.toString();
    }
    this.httpService.httpPostSuccess('menu/save', body, data => {
      this.noticeService.success('添加成功');
      this.back();
    });
  }


  private getMenuArray() {
    this.httpService.httpPostSuccess('menu/list', {}, response => {
      this.menuArray.push(this.nothingMenu);
      response.data.forEach(element => {
        this.menuArray.push(element);
      });
    });
  }

  private getById() {
    this.httpService.httpGetSuccess('menu/query/' + this.id, response => {
      this.menu.setDataValue(response.data);
    });
  }

  private getPids(pid: number) {
    this.menuArray.forEach(menu => {
      if (menu.id === pid) {
        this.pids.push(pid);
        if (menu.pid) {
          this.getPids(menu.pid);
        }
      }
    });
  }

}
